<?php
namespace App\Workers;

use Workerman\Worker;
use App\Services\CollegeSpiderService;

class CollegeSpiderWorker
{
    public static function run(Worker $worker, $collegeSpiderService, $batchSize = 20, $limit = null, $options = [])
    {
        $worker->onWorkerStart = function($worker) use ($collegeSpiderService, $batchSize, $limit, $options) {
            $startTime = time();
            echo "[".date('Y-m-d H:i:s')."] Worker {$worker->id} 启动\n";

            try {
                // 获取待采集院校
                $colleges = $collegeSpiderService->getColleges($limit);
                
                if ($colleges->isEmpty()) {
                    echo "[".date('Y-m-d H:i:s')."] 没有发现待采集的院校\n";
                    return;
                }
                
                $total = $colleges->count();
                echo "[".date('Y-m-d H:i:s')."] 共发现 {$total} 所院校待采集\n";
                
                $successCount = 0;
                $batches = array_chunk($colleges->all(), $batchSize);
                
                foreach ($batches as $batch) {
                    foreach ($batch as $college) {
                        $retry = 0;
                        $maxRetry = 3;
                        $processed = false;
                        
                        while ($retry < $maxRetry && !$processed) {
                            try {
                                echo "[".date('Y-m-d H:i:s')."] 正在采集: {$college->college_name}...";
                                $result = $collegeSpiderService->processCollege($college);
                                
                                if ($result) {
                                    $successCount++;
                                    echo "成功\n";
                                    $processed = true;
                                } else {
                                    throw new \Exception("采集失败");
                                }
                            } catch (\Exception $e) {
                                $retry++;
                                echo "失败(尝试{$retry}/{$maxRetry}): ".$e->getMessage()."\n";
                                if ($retry >= $maxRetry) {
                                    echo "[".date('Y-m-d H:i:s')."] 放弃采集: {$college->college_name}\n";
                                }
                                sleep(1);
                            }
                        }
                    }
                }
                
                // 统计结果
                $endTime = time();
                $duration = $endTime - $startTime;
                $successRate = $total > 0 ? round(($successCount / $total) * 100, 2) : 0;
                
                echo "\n===== 采集结果统计 =====\n";
                echo "开始时间: ".date('Y-m-d H:i:s', $startTime)."\n";
                echo "结束时间: ".date('Y-m-d H:i:s', $endTime)."\n";
                echo "总耗时: ".gmdate('H:i:s', $duration)."\n";
                echo "总院校数: {$total}\n";
                echo "成功采集: {$successCount}\n";
                echo "成功率: {$successRate}%\n";
                echo "平均速度: ".round($successCount/max(1, $duration/60), 2)." 条/分钟\n";
                echo "========================\n";
                
            } catch (\Exception $e) {
                echo "[".date('Y-m-d H:i:s')."] 采集过程中发生错误: ".$e->getMessage()."\n";
            }
        };
    }
}
